<?php

namespace backend\modules\android_app_versions\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\modules\android_app_versions\models\ApiToken;

/**
 * ApiTokenSearch represents the model behind the search form about `backend\modules\android_app_versions\models\ApiToken`.
 */
class ApiTokenSearch extends ApiToken
{
    public $u_name;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['tk_id', 'tk_uid', 'tk_expiration'], 'integer'],
            [['tk_token', 'u_name'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ApiToken::find();
        $query->joinWith(['member as member']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $dataProvider->sort->attributes['u_name'] = [
            'asc' => ['member.u_name' => SORT_ASC],
            'desc' => ['member.u_name' => SORT_DESC],
            'label' => 'Member Name'
        ];

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'tk_id' => $this->tk_id,
            'tk_uid' => $this->tk_uid,
            'tk_expiration' => $this->tk_expiration,
        ]);

        $query->andFilterWhere(['like', 'tk_token', $this->tk_token]);
        $query->andFilterWhere(['like', 'member.u_name', $this->u_name]) ;

        return $dataProvider;
    }
}
